const express = require("express");
const router = express.Router();
const passport = require("passport");
const Discover = require("../../../models/Discover");
const auth = passport.authenticate("jwt", { session: false });
const errorHandler = require("../../../middlewares/errorHandler");

// @route  GET api/discovers/test
router.get("/test", (req, res) => res.json({ msg: "discovers works" }));

// @route  POST api/discovers/add
router.post("/add", auth, async (req, res) => {
  try {
    const { title, image, content, tags } = req.body;
    const newDiscover = {
      user_id: req.user.id,
      avatar: req.user.avatar,
      name: req.user.name,
      title,
      image,
      content,
      tags, // 直接从请求中获取tags
    };

    const discover = await Discover.create(newDiscover);
    console.log("添加数据成功:", discover);
    res.status(200).json({ success: true, data: discover });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/discovers
router.get("/", auth, async (req, res) => {
  try {
    const discovers = await Discover.find();
    console.log("获取数据成功:", discovers);
    res
      .status(200)
      .json({ success: true, count: discovers.length, data: discovers });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  GET api/discovers/:id
router.get("/:id", auth, async (req, res) => {
  try {
    const discover = await Discover.findById(req.params.id);
    if (!discover) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("获取数据成功", discover);
    res.status(200).json({ success: true, data: discover });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  POST api/discovers/edit
router.post("/edit", auth, async (req, res) => {
  try {
    const { _id, ...updateData } = req.body;
    updateData.updatedAt = Date.now();
    const discover = await Discover.findByIdAndUpdate(_id, updateData, {
      new: true,
    });
    if (!discover) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("编辑数据成功:", discover);
    res.status(200).json({ success: true, data: discover });
  } catch (err) {
    errorHandler(res, err);
  }
});

// @route  DELETE api/discovers/delete
router.delete("/delete", auth, async (req, res) => {
  try {
    const { _id } = req.body;
    const discover = await Discover.findByIdAndRemove(_id);
    if (!discover) {
      console.error("未查找到数据");
      return res.status(404).json({ success: false, error: "未查找到数据" });
    }
    console.log("删除数据成功:", discover);
    res.status(200).json({ success: true, data: discover });
  } catch (err) {
    errorHandler(res, err);
  }
});

module.exports = router;
